//
//  TokDocManageUtilities.m
//  tok
//
//  Created by sijian on 12-9-19.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TokDocManageUtilities.h"
#include <sys/xattr.h>

@implementation TokDocManageUtilities
+(NSString *) getAppWorkPath
{
    static NSString *appDocPath;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    appDocPath = [paths objectAtIndex:0];
    return appDocPath;
    
}

+(NSString *) getDBDocPath
{
    static NSString *dbDocPath;
    dbDocPath = [TokDocManageUtilities getAppWorkPath];
    return dbDocPath;
}

+(NSString *) getFileDocPath
{
    static NSString *imgDocPath;
    imgDocPath = [[TokDocManageUtilities getAppWorkPath] stringByAppendingPathComponent:@"TCC_recordFiles//"];
    return imgDocPath;
}

+(void) createFilePath:(NSString *) filePath{
    NSFileManager *fileManager = [[NSFileManager alloc]init];
//    BOOL isDirExist = [fileManager fileExistsAtPath:filePath isDirectory:YES];
//    if(!isDirExist){
//       BOOL bCreateDir = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
//        if(!bCreateDir){
//            NSLog(@"Create Audio Directory Failed.");
//        }
//    }
    
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if(!(isDirExist && isDir)){
        BOOL bCreateDir = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
//            NSLog(@"Create Audio Directory Failed.");
        }
        NSLog(@"%@",filePath);
    }
    [fileManager release];
}

+(BOOL)isExistWithDocPath:(NSString *)docPath
{
   	NSFileManager *filemgr;
    
	filemgr = [NSFileManager defaultManager];
    BOOL isDirExist = [filemgr fileExistsAtPath:docPath];
    [filemgr release];
    return isDirExist;
}

+(BOOL)copyFileWithOldPath:(NSString *)oldPath toNewPath:(NSString *)newPath
{
   	NSFileManager *filemgr;
    
	filemgr = [NSFileManager defaultManager];
    BOOL isSuccess = NO;
    isSuccess = [filemgr copyItemAtPath: oldPath toPath: newPath error: NULL];

	[filemgr release];
    return isSuccess;
    
}

//获得某个范围内的屏幕图像
+(UIImage *)getImageFromImage: (UIImage *) bigImage atFrame:(CGRect)myImageRect{
    //大图bigImage
    CGImageRef imageRef = bigImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, myImageRect, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    return smallImage;
}

//获取数据存储主键，主键格式为年月日时分秒
+(NSString *) getinsertPk{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //输出格式为：2010-10-27 10:22:13
    //NSLog(@”%@”,currentDateStr);
    //alloc后对不使用的对象别忘了release
    [dateFormatter release];
    return currentDateStr;
}

#pragma mark - doc utilites


#pragma mark - file utilites
+(NSData *)readFileContentWithFilePath:(NSString *)filePath
{
    NSFileManager *filemgr;
	NSData *databuffer  =nil;
    filemgr = [NSFileManager defaultManager];
    
    //判断文件是否存在
    if ([filemgr fileExistsAtPath: filePath ] == YES)
    {
        //读文件
        databuffer = [filemgr contentsAtPath: filePath ];
    }

	[filemgr release];
    return databuffer;
}

//获取指定路径下的图片文件
+(NSMutableArray *) getImageWithDocPath:(NSString *)docPath{
    NSMutableArray *sourceImages = [NSMutableArray arrayWithCapacity:20];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //在这里获取应用程序Documents文件夹里的文件及文件夹列表
    NSString *documentDir = docPath;
    NSError *error = nil;
    NSArray *fileList = [[NSArray alloc] init];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:docPath error:&error];
    //    NSLog(@"the bugs pk  is %@",pkBug);
    for(NSString *imageName in fileList){
        //        NSLog(@" the index file imageName is %@",imageName);
        if([imageName hasSuffix:@"png"]||[imageName hasSuffix:@"jpg"]){
            NSString *tempStr=[documentDir stringByAppendingPathComponent:imageName];
            //            NSLog(@" the index file path is %@",tempStr);
            NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
            BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
            if (!isDirectory) {
                NSString *filePath=[documentDir stringByAppendingPathComponent:imageName];
                NSData *myData=[fileManager contentsAtPath:filePath];
                UIImage *myImage=[UIImage imageWithData:myData];
                [sourceImages addObject:myImage];
            }
        }
    }
    return sourceImages;
}


//删除指定目录下的文件
+(BOOL)deleteFileWithPath:(NSString *)filePath{
    NSURL *fileUrl = [NSURL URLWithString:filePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDelete=[fileManager removeItemAtURL:fileUrl error:nil];
    return isDelete;
}


//删除目录及其目录下的文件
+(BOOL)deleteDictionaryAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDelete= [fileManager removeItemAtPath:filePath error:nil];
    return isDelete;
}

//标记文件目录不需要备份
+ (BOOL)addSkipBackupAttributeToFilePath:(NSString *)filePath {
    NSURL *dbURLPath = [NSURL URLWithString:filePath];
    return [TokDocManageUtilities addSkipBackupAttributeToItemAtURL:dbURLPath];
}


//标记文件目录不需要备份
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
    const char* filePath = [[URL path] fileSystemRepresentation];
    
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}

//获取文件名称
+(NSString *)getFileName:(NSString *)projCode andWithFile:(NSString *)classCode{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyMMddHHmmss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    static NSString *fileName;
    fileName = [projCode stringByAppendingString:@"_"];
    fileName = [fileName stringByAppendingString:classCode];
    fileName = [fileName stringByAppendingString:@"_"];
    fileName=[fileName stringByAppendingString:currentDateStr];
    return fileName;
}

@end
